package com.example.qihuibao.utils;

import android.app.ActivityManager;
import android.content.Context;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Calendar;
import java.util.List;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

public class CommonUtil {
    //检测是否能够上网
    public static boolean isConnectNetwork() {
        String url = "http://www.baidu.com/";//不要用https
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        HttpResponse response = null;
        try {
            response = client.execute(new HttpGet(url));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {//没连wifi、连wifi有代理但代理不能上网的场景
            e.printStackTrace();
        }
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            try {
                HttpURLConnection mHttpUrlConnection = (HttpURLConnection) new URL(url).openConnection();
                mHttpUrlConnection.setConnectTimeout(5000);// 设置连接超时
                try {
                    mHttpUrlConnection.setRequestMethod("GET");
                    try {
                        if (mHttpUrlConnection.getResponseCode() == 200) {//对需要认证的wifi有效
                            return true;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (ProtocolException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 判断时间是否在时间段内
     * @param time System.currentTimeMillis()
     * @param strDateBegin 开始时间 00:00:00
     * @param strDateEnd 结束时间 00:05:00
     * @return
     */
    public static boolean isInTime(long time, String strDateBegin, String strDateEnd) {
        Calendar calendar = Calendar.getInstance();
        // 处理开始时间
        String[] startTime = strDateBegin.split(":");
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        long startTimeL = calendar.getTimeInMillis();
        // 处理结束时间
        String[] endTime = strDateEnd.split(":");
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(endTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(endTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        long endTimeL = calendar.getTimeInMillis();
        return time >= startTimeL && time <= endTimeL;
    }

    //时分秒转毫秒
    public static long time2Millis(String time) {
        String[] startTime = time.split(":");
        if (startTime.length < 3) {
            return System.currentTimeMillis();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[1]));
        calendar.set(Calendar.SECOND, Integer.parseInt(startTime[2]));
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    //毫秒转时分秒
    public static String millis2Time(long mss) {
        long second = mss/1000;
        long hours = second / 3600;
        long minutes = (second - hours*3600) / 60;
        long seconds = second - hours*3600 - minutes*60;
        return hours/10+""+hours%10+":"+minutes/10+""+minutes%10+":"+seconds/10+""+seconds%10;
    }

//    public static org.json.JSONObject getParams(org.json.JSONObject data) {
//        org.json.JSONObject params = new org.json.JSONObject();
//        try {
//            params.put("data", encryptBase64ByRsaPublicKey(data.toString(), Config.PUBLIC_KEY));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return params;
//    }

    /**
     * RSA公钥加密
     *
     * @param data          被加密的字符串
     * @param publicKey     RSA私钥
     *
     * @return Base64字符串密文
     */
    public static String encryptBase64ByRsaPublicKey(String data, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.encryptBase64(data, KeyType.PublicKey);
    }

    //RSA解密
    public static String decryptBase64ByRsaPublicKey(String data, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.decryptStr(data, KeyType.PublicKey);
    }

    //检查app是否已经运行
    public static boolean ifAppProcessExit(Context context, String pkgName) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(pkgName) && info.baseActivity.getPackageName().equals(pkgName)) {
                return true;
            }
        }
        return false;
    }

}
